package com.xiaowenxiong.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by 15c on 2017/5/21.
 */
//用于超级用户登录
@Controller
public class LoginController {
    /**
     * 得到主页
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "student/main";
    }

    /**
     * 得到登录页
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String getLoginJsp() {
        return "student/login";
    }

    /**
     * 处理登录提交的表单
     *
     * @param model               用于传error
     * @param httpServletRequest  用于获取表单参数
     * @param httpServletResponse 用于请求重定向
     * @param session             用于存用户的一些信息
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Model model, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, HttpSession session) throws IOException {
        String uname = httpServletRequest.getParameter("uname");
        String password = httpServletRequest.getParameter("password");
        if ("wang".equals(uname) && "wanggaowen".equals(password)) {
            session.setAttribute("admin", uname);
            //请求重定向
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/index");
        } else if ("".equals(uname) || "".equals(password)) {
            String error = "用户名与密码不可以为空！";
            model.addAttribute("error", error);
            return "student/login";
        } else if (!"wang".equals(uname) || !"wanggaowen".equals(password)) {
            String error = "登录失败，账户或密码错误！";
            model.addAttribute("error", error);
            return "student/login";
        }
        return null;

    }

    /**
     * 用于处理登出请求
     *
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpSession session) throws IOException {
            session.removeAttribute("admin");
        return "student/main";
    }
}
